package com.oly.cms.web.config;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.oly.cms.general.service.taglib.WebTag;

@Component
public class PageErrorViewResolver implements ErrorViewResolver {

    @Autowired
    private WebTag webTag;

    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        ModelAndView modelAndView = new ModelAndView();

        String path = model.get("path").toString();
        String themeName = "default";
        String[] sp = path.split("/");
        // 截取主题名
        if (path.startsWith("/static") && sp.length > 2) {
            themeName = sp[2];
        } else if (sp.length > 1) {
            themeName = sp[1];
        }
        if (!webTag.mapTheme().containsKey(themeName)) {
            themeName = "default";
        }
        modelAndView.addAllObjects(model);
        modelAndView.addObject("themeName", themeName);
        return getModelAndView(modelAndView, String.valueOf(status.value()), themeName);
    }

    private ModelAndView getModelAndView(ModelAndView modelAndView, String errorCode, String themeName) {
        if ("404".equals(errorCode)) {
            modelAndView.setViewName("/" + themeName + "/pages/error/404");
        } else if ("403".equals(errorCode)) {
            modelAndView.setViewName("/" + themeName + "/pages/error/403");
        } else if ("500".equals(errorCode)) {
            modelAndView.setViewName("/" + themeName + "/pages/error/500");
        } else {
            modelAndView.setViewName("/" + themeName + "/pages/error/404");
        }
        return modelAndView;
    }

}